from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Dict, List, Any
from pydantic import BaseModel
from loguru import logger

from app.models.db import get_async_session, User
from app.models.user import current_active_user



router = APIRouter(prefix="/assistant", tags=["智能助手"])





class TaskConfigRequest(BaseModel):
    task_type: str  # 'api_function' or 'data_query'
    task_name: str
    description: str = None
    priority: int = 0


class ApiConfigRequest(BaseModel):
    task_config_id: str
    function_name: str
    description: str = None
    endpoint_url: str
    http_method: str = "POST"
    headers: Dict[str, str] = None
    auth_config: Dict[str, Any] = None
    parameters_schema: Dict[str, Any] = None
    required_params: List[str] = None
    intent_keywords: List[str] = None
    intent_examples: List[str] = None






@router.post("/task-config")
async def create_task_config(
    request: TaskConfigRequest,
    current_user: User = Depends(current_active_user),
    db: AsyncSession = Depends(get_async_session)
):
    """创建任务配置"""
    try:
        from app.models.db import TaskConfig
        import uuid
        from datetime import datetime
        
        task_config = TaskConfig(
            id=str(uuid.uuid4()),
            task_type=request.task_type,
            task_name=request.task_name,
            description=request.description,
            priority=request.priority,
            is_active=True,
            created_at=datetime.utcnow(),
            updated_at=datetime.utcnow()
        )
        
        db.add(task_config)
        await db.commit()
        
        return {
            "status": "success",
            "message": "任务配置创建成功",
            "task_config_id": task_config.id
        }
        
    except Exception as e:
        logger.error(f"创建任务配置失败: {str(e)}")
        await db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建任务配置失败: {str(e)}"
        )


@router.post("/api-config")
async def create_api_config(
    request: ApiConfigRequest,
    current_user: User = Depends(current_active_user),
    db: AsyncSession = Depends(get_async_session)
):
    """创建API函数配置"""
    try:
        from app.models.db import ApiFunction
        import uuid
        from datetime import datetime
        
        api_function = ApiFunction(
            id=str(uuid.uuid4()),
            task_config_id=request.task_config_id,
            function_name=request.function_name,
            description=request.description,
            endpoint_url=request.endpoint_url,
            http_method=request.http_method,
            headers=request.headers,
            auth_config=request.auth_config,
            parameters_schema=request.parameters_schema,
            required_params=request.required_params,
            intent_keywords=request.intent_keywords,
            intent_examples=request.intent_examples,
            is_active=True,
            created_at=datetime.utcnow(),
            updated_at=datetime.utcnow()
        )
        
        db.add(api_function)
        await db.commit()
        
        return {
            "status": "success", 
            "message": "API函数配置创建成功",
            "api_function_id": api_function.id
        }
        
    except Exception as e:
        logger.error(f"创建API函数配置失败: {str(e)}")
        await db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建API函数配置失败: {str(e)}"
        )


@router.get("/task-configs")
async def get_task_configs(
    current_user: User = Depends(current_active_user),
    db: AsyncSession = Depends(get_async_session)
):
    """获取所有任务配置"""
    try:
        from sqlalchemy import select
        from app.models.db import TaskConfig
        
        query = select(TaskConfig).where(TaskConfig.is_active == True).order_by(TaskConfig.priority.desc())
        result = await db.execute(query)
        task_configs = result.scalars().all()
        
        configs_data = []
        for config in task_configs:
            configs_data.append({
                "id": config.id,
                "task_type": config.task_type,
                "task_name": config.task_name,
                "description": config.description,
                "priority": config.priority,
                "created_at": config.created_at.isoformat() if config.created_at else None
            })
        
        return {
            "status": "success",
            "task_configs": configs_data
        }
        
    except Exception as e:
        logger.error(f"获取任务配置失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取任务配置失败: {str(e)}"
        )


@router.get("/api-functions/{task_config_id}")
async def get_api_functions(
    task_config_id: str,
    current_user: User = Depends(current_active_user),
    db: AsyncSession = Depends(get_async_session)
):
    """获取指定任务配置的API函数"""
    try:
        from sqlalchemy import select
        from app.models.db import ApiFunction
        
        query = select(ApiFunction).where(
            ApiFunction.task_config_id == task_config_id,
            ApiFunction.is_active == True
        )
        result = await db.execute(query)
        api_functions = result.scalars().all()
        
        functions_data = []
        for func in api_functions:
            functions_data.append({
                "id": func.id,
                "function_name": func.function_name,
                "description": func.description,
                "endpoint_url": func.endpoint_url,
                "http_method": func.http_method,
                "required_params": func.required_params,
                "intent_keywords": func.intent_keywords,
                "intent_examples": func.intent_examples,
                "created_at": func.created_at.isoformat() if func.created_at else None
            })
        
        return {
            "status": "success",
            "api_functions": functions_data
        }
        
    except Exception as e:
        logger.error(f"获取API函数配置失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取API函数配置失败: {str(e)}"
        )


@router.get("/api-functions")
async def get_all_api_functions(
    skip: int = 0,
    limit: int = 20,
    search: str = None,
    current_user: User = Depends(current_active_user),
    db: AsyncSession = Depends(get_async_session)
):
    """获取所有API函数列表（用于管理界面）"""
    try:
        from sqlalchemy import select, func, or_
        from app.models.db import ApiFunction
        
        # 构建查询条件
        query = select(ApiFunction).where(ApiFunction.is_active == True)
        
        # 添加搜索条件
        if search:
            search_condition = or_(
                ApiFunction.function_name.ilike(f"%{search}%"),
                ApiFunction.description.ilike(f"%{search}%"),
                ApiFunction.endpoint_url.ilike(f"%{search}%")
            )
            query = query.where(search_condition)
        
        # 获取总数
        count_query = select(func.count(ApiFunction.id)).where(ApiFunction.is_active == True)
        if search:
            count_query = count_query.where(search_condition)
        
        total_result = await db.execute(count_query)
        total = total_result.scalar()
        
        # 分页查询
        query = query.offset(skip).limit(limit).order_by(ApiFunction.created_at.desc())
        result = await db.execute(query)
        api_functions = result.scalars().all()
        
        functions_data = []
        for func in api_functions:
            functions_data.append({
                "id": func.id,
                "function_name": func.function_name,
                "description": func.description,
                "endpoint_url": func.endpoint_url,
                "http_method": func.http_method,
                "required_params": func.required_params,
                "intent_keywords": func.intent_keywords,
                "intent_examples": func.intent_examples,
                "is_active": func.is_active,
                "created_at": func.created_at.isoformat() if func.created_at else None
            })
        
        return {
            "status": "success",
            "data": {
                "items": functions_data,
                "total": total,
                "skip": skip,
                "limit": limit
            }
        }
        
    except Exception as e:
        logger.error(f"获取API函数列表失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取API函数列表失败: {str(e)}"
        )


@router.get("/api-config/{api_id}")
async def get_api_function_detail(
    api_id: str,
    current_user: User = Depends(current_active_user),
    db: AsyncSession = Depends(get_async_session)
):
    """获取API函数详情"""
    try:
        from sqlalchemy import select
        from app.models.db import ApiFunction
        
        query = select(ApiFunction).where(ApiFunction.id == api_id)
        result = await db.execute(query)
        api_function = result.scalar_one_or_none()
        
        if not api_function:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="API函数不存在"
            )
        
        return {
            "status": "success",
            "data": {
                "id": api_function.id,
                "task_config_id": api_function.task_config_id,
                "function_name": api_function.function_name,
                "description": api_function.description,
                "endpoint_url": api_function.endpoint_url,
                "http_method": api_function.http_method,
                "headers": api_function.headers,
                "auth_config": api_function.auth_config,
                "parameters_schema": api_function.parameters_schema,
                "required_params": api_function.required_params,
                "intent_keywords": api_function.intent_keywords,
                "intent_examples": api_function.intent_examples,
                "is_active": api_function.is_active,
                "created_at": api_function.created_at.isoformat() if api_function.created_at else None,
                "updated_at": api_function.updated_at.isoformat() if api_function.updated_at else None
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取API函数详情失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取API函数详情失败: {str(e)}"
        )


@router.put("/api-config/{api_id}")
async def update_api_function(
    api_id: str,
    request: ApiConfigRequest,
    current_user: User = Depends(current_active_user),
    db: AsyncSession = Depends(get_async_session)
):
    """更新API函数配置"""
    try:
        from sqlalchemy import select
        from app.models.db import ApiFunction
        from datetime import datetime
        
        # 查找API函数
        query = select(ApiFunction).where(ApiFunction.id == api_id)
        result = await db.execute(query)
        api_function = result.scalar_one_or_none()
        
        if not api_function:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="API函数不存在"
            )
        
        # 更新字段
        api_function.task_config_id = request.task_config_id
        api_function.function_name = request.function_name
        api_function.description = request.description
        api_function.endpoint_url = request.endpoint_url
        api_function.http_method = request.http_method
        api_function.headers = request.headers
        api_function.auth_config = request.auth_config
        api_function.parameters_schema = request.parameters_schema
        api_function.required_params = request.required_params
        api_function.intent_keywords = request.intent_keywords
        api_function.intent_examples = request.intent_examples
        api_function.updated_at = datetime.utcnow()
        
        await db.commit()
        
        return {
            "status": "success",
            "message": "API函数配置更新成功",
            "api_function_id": api_function.id
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新API函数配置失败: {str(e)}")
        await db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新API函数配置失败: {str(e)}"
        )


@router.delete("/api-config/{api_id}")
async def delete_api_function(
    api_id: str,
    current_user: User = Depends(current_active_user),
    db: AsyncSession = Depends(get_async_session)
):
    """删除API函数配置"""
    try:
        from sqlalchemy import select
        from app.models.db import ApiFunction
        
        # 查找API函数
        query = select(ApiFunction).where(ApiFunction.id == api_id)
        result = await db.execute(query)
        api_function = result.scalar_one_or_none()
        
        if not api_function:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="API函数不存在"
            )
        
        # 软删除：设置is_active为False
        api_function.is_active = False
        api_function.updated_at = datetime.now()
        
        await db.commit()
        
        return {
            "status": "success",
            "message": "API函数配置删除成功"
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除API函数配置失败: {str(e)}")
        await db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"删除API函数配置失败: {str(e)}"
        )


@router.patch("/api-config/{api_id}/toggle")
async def toggle_api_function(
    api_id: str,
    request: Dict[str, bool],
    current_user: User = Depends(current_active_user),
    db: AsyncSession = Depends(get_async_session)
):
    """启用/禁用API函数"""
    try:
        from sqlalchemy import select
        from app.models.db import ApiFunction
        from datetime import datetime
        
        # 查找API函数
        query = select(ApiFunction).where(ApiFunction.id == api_id)
        result = await db.execute(query)
        api_function = result.scalar_one_or_none()
        
        if not api_function:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="API函数不存在"
            )
        
        # 切换状态
        api_function.is_active = request.get("is_active", not api_function.is_active)
        api_function.updated_at = datetime.utcnow()
        
        await db.commit()
        
        status_text = "启用" if api_function.is_active else "禁用"
        return {
            "status": "success",
            "message": f"API函数已{status_text}",
            "is_active": api_function.is_active
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"切换API函数状态失败: {str(e)}")
        await db.rollback()
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"切换API函数状态失败: {str(e)}"
        )


@router.post("/api-test/{api_id}")
async def test_api_function(
    api_id: str,
    request: Dict[str, Any],
    current_user: User = Depends(current_active_user),
    db: AsyncSession = Depends(get_async_session)
):
    """测试API函数"""
    try:
        from sqlalchemy import select
        from app.models.db import ApiFunction
        from app.ai.task_execution_engine import TaskExecutionEngine
        
        # 查找API函数
        query = select(ApiFunction).where(ApiFunction.id == api_id)
        result = await db.execute(query)
        api_function = result.scalar_one_or_none()
        
        if not api_function:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="API函数不存在"
            )
        
        # 使用任务执行引擎测试API
        task_engine = TaskExecutionEngine()
        test_params = request.get("params", {})
        
        # 构建测试任务
        test_task = {
            "task_type": "api_function",
            "api_function_id": api_id,
            "parameters": test_params
        }
        
        # 执行测试
        result = await task_engine._execute_api_function(
            api_function, test_params, "test_session", "test_user", db
        )
        
        return {
            "status": "success",
            "message": "API测试完成",
            "data": result
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"API函数测试失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"API函数测试失败: {str(e)}"
        )